<%--
  Created by IntelliJ IDEA.
  User: 吴超
  Date: 2022/4/26
  Time: 16:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style>

    </style>
    <script src="../js/jquery.js"></script>
</head>
<body>
<input type="text" id="t1" name="name">
<input type="button" id="bt1" name="bt" value="异步点我1">
<input type="button" id="bt2" name="bt" value="异步点我2查">
<span></span>
<ul></ul>
<script>
    /*var arr=[{name:"超哥"},{name:"jiji"}];
    $.each(arr,function () {
        var li="<li>"+this.name+"</li>";
        $("ul").append(li);
    });*/
    const getJSON = function(url) {
        const promise = new Promise(function(resolve, reject){
            const handler = function() {
                if (this.readyState !== 4) { return; }
                if (this.status === 200) { resolve(this.response);
                } else { reject( new Error(this.statusText)); }
            };
            const client = new XMLHttpRequest();
            client.open("GET", url);
            client.onreadystatechange = handler;
            client.responseType = "json";
            client.setRequestHeader("Accept", "application");
            client.send();
        });
        return promise;
    };

    $("#bt2").click(function () {
        getJSON("${pageContext.request.contextPath}/ServletAjax1").then(function(data) {
            $.each(data,function () {
                var li="<li>"+this.name+"</li>";
                $("ul").append(li);
            });
            console.log('请求成功');
        }, function(error) {
            console.error('请求失败');
        });


     //var tt=$("#t1").val();
     /*$("ul").html("");
     $.ajax({
         url:"${pageContext.request.contextPath}/ServletAjax1",
         type:"get",
         dataType:"json",
         success:function (data) {
             $.each(data,function () {
                 var li="<li>"+this.name+"</li>";
                 $("ul").append(li);
             })
         }

     });*/
 });

$("#bt1").click(function () {
    //alert("点我干啥");
    var tt=$("#t1").val();
    //alert(tt);
    var xml=new XMLHttpRequest();//对象
    xml.onreadystatechange=callback;
    var url="${pageContext.request.contextPath}/ServletAjax1?tt="+tt;
    xml.open("GET",url,true);
    xml.send(null);
    function callback() {
        if(xml.readyState== 4&&xml.status==200){
            var data=xml.responseText;
           alert(data);
            if(data.trim()=="y"){
              $("#bt1").css("background-color","red");
            }else{
                $("#bt1").css("background-color","gray");
                //alert("异步错误");
            }
        }
    }

});
</script>
</body>
</html>
